package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";
    private static final String VALUE_PREFIXX = UUID.randomUUID().toString(true) + "-";
    private static final DefaultRedisScript<Long> UNLOCK_SCIPT;

    static {
        UNLOCK_SCIPT = new DefaultRedisScript<>();
        UNLOCK_SCIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSc) {
        String lockValue = VALUE_PREFIXX + Thread.currentThread().getId();
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(
                KEY_PREFIX + name, lockValue, timeoutSc, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);
    }

    @Override
    public void unLock() {
        // 调用 Lua 脚本
        stringRedisTemplate.execute(
                UNLOCK_SCIPT,
                Collections.singletonList(KEY_PREFIX + name),
                VALUE_PREFIXX + Thread.currentThread().getId()
        );
    }


//    @Override
//    public void unLock() {
//        String currentValue = VALUE_PREFIXX + Thread.currentThread().getId();
//        String lockValue = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//        if (currentValue.equals(lockValue)){
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//        }
//    }
}
